package com.example.common.domain.pojo.Converter;



import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import lombok.SneakyThrows;
import java.util.LinkedHashMap;
import java.util.Map;

@Converter(autoApply = false)
public class MapToJsonConverter implements AttributeConverter<Map<String, String>, String> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    // 序列化：Map → JSON字符串（使用 LinkedHashMap 保持顺序）
    @Override
    @SneakyThrows
    public String convertToDatabaseColumn(Map<String, String> attribute) {
        if (attribute == null) {
            return null;
        }
        return objectMapper.writeValueAsString(attribute);
    }

    // 反序列化：JSON字符串 → LinkedHashMap（保留顺序）
    @Override
    @SneakyThrows
    public Map<String, String> convertToEntityAttribute(String dbData) {
        if (dbData == null) {
            return new LinkedHashMap<>();
        }
        // 使用 TypeReference 指定返回类型为 LinkedHashMap
        return objectMapper.readValue(dbData, new TypeReference<LinkedHashMap<String, String>>() {});
    }
}
